import { create } from 'zustand';

interface ThemeState {
  isDarkMode: boolean;
  primaryColor: string;
  fontSize: 'small' | 'medium' | 'large';
  borderRadius: 'small' | 'medium' | 'large';
  compactMode: boolean;
  toggleDarkMode: () => void;
  setPrimaryColor: (color: string) => void;
  setFontSize: (size: 'small' | 'medium' | 'large') => void;
  setBorderRadius: (radius: 'small' | 'medium' | 'large') => void;
  setCompactMode: (compact: boolean) => void;
  applyTheme: () => void;
}

// 获取系统暗黑模式偏好
const prefersDarkMode = window.matchMedia && 
  window.matchMedia('(prefers-color-scheme: dark)').matches;

export const useThemeStore = create<ThemeState>()((set, get) => ({
  isDarkMode: prefersDarkMode,
  primaryColor: '#1890ff',
  fontSize: 'medium' as const,
  borderRadius: 'medium' as const,
  compactMode: false,
  
  toggleDarkMode: () => {
    set((state) => ({ isDarkMode: !state.isDarkMode }));
    get().applyTheme();
  },
  
  setPrimaryColor: (color: string) => {
    set({ primaryColor: color });
    get().applyTheme();
  },
  
  setFontSize: (size: 'small' | 'medium' | 'large') => {
    set({ fontSize: size });
    get().applyTheme();
  },
  
  setBorderRadius: (radius: 'small' | 'medium' | 'large') => {
    set({ borderRadius: radius });
    get().applyTheme();
  },
  
  setCompactMode: (compact: boolean) => {
    set({ compactMode: compact });
    get().applyTheme();
  },
  
  applyTheme: () => {
    const { isDarkMode, primaryColor, fontSize, borderRadius, compactMode } = get();
    
    // 应用暗黑模式
    document.documentElement.classList.toggle('dark-theme', isDarkMode);
    document.documentElement.classList.toggle('light-theme', !isDarkMode);
    
    // 应用主题色
    document.documentElement.style.setProperty('--primary-color', primaryColor);
    document.documentElement.style.setProperty('--primary-color-hover', adjustColor(primaryColor, 10));
    document.documentElement.style.setProperty('--primary-color-active', adjustColor(primaryColor, 20));
    document.documentElement.style.setProperty('--primary-color-outline', `${primaryColor}20`);
    
    // 应用字体大小
    const fontSizeMap: Record<'small' | 'medium' | 'large', string> = {
      small: '12px',
      medium: '14px',
      large: '16px',
    };
    document.documentElement.style.setProperty('--font-size-base', fontSizeMap[fontSize]);
    
    // 应用圆角大小
    const borderRadiusMap: Record<'small' | 'medium' | 'large', string> = {
      small: '2px',
      medium: '4px',
      large: '8px',
    };
    document.documentElement.style.setProperty('--border-radius-base', borderRadiusMap[borderRadius]);
    
    // 应用紧凑模式
    document.documentElement.classList.toggle('compact-mode', compactMode);
  },
}));

// 辅助函数：调整颜色明度
function adjustColor(color: string, amount: number): string {
  // 简单实现，实际项目可能需要更复杂的颜色处理
  return color;
} 